package com.pengchuang.ACS.auth.service.impl;

import com.pengchuang.ACS.admin.api.dto.OAuth2ClientDTO;
import com.pengchuang.ACS.admin.api.feign.OAuthClientFeignClient;
import com.pengchuang.ACS.common.enums.PasswordEncoderTypeEnum;
import com.pengchuang.ACS.common.utils.FeignUtil;
import com.pengchuang.ACS.common.utils.R;
import lombok.RequiredArgsConstructor;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.security.oauth2.provider.ClientDetails;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.security.oauth2.provider.NoSuchClientException;
import org.springframework.security.oauth2.provider.client.BaseClientDetails;
import org.springframework.stereotype.Service;

@Service
@RequiredArgsConstructor
public class ClientDetailsServiceImpl implements ClientDetailsService {
    private final OAuthClientFeignClient oAuthClientFeignClient;
    @Override
    @Cacheable(cacheNames = "auth", key = "'oauth-client:'+#clientId")
    public ClientDetails loadClientByClientId(String clientId) {
        // 通过feign 调用admin服务获取client信息
        R result = oAuthClientFeignClient.getOAuth2ClientById(clientId);
        if (R.ok().get("code").equals(result.get("code"))) {
            // feign 转换很恶心
            OAuth2ClientDTO client = FeignUtil.convertValue(result.get("result"), OAuth2ClientDTO.class);
            BaseClientDetails clientDetails = new BaseClientDetails(
                    client.getClientId(),
                    client.getResourceIds(),
                    client.getScope(),
                    client.getAuthorizedGrantTypes(),
                    client.getAuthorities(),
                    client.getWebServerRedirectUri());
            clientDetails.setClientSecret(PasswordEncoderTypeEnum.NOOP.getPrefix() + client.getClientSecret());
            clientDetails.setAccessTokenValiditySeconds(client.getAccessTokenValidity());
            clientDetails.setRefreshTokenValiditySeconds(client.getRefreshTokenValidity());
            return clientDetails;
        } else {
            throw new NoSuchClientException((String) result.get("msg"));
        }
    }
}
